package com.sharding.transaction.algorithm;

import com.google.common.collect.Range;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingValue;

import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.LinkedHashSet;

public class OrderDatabaseShardingRangeAlgorithm implements RangeShardingAlgorithm<Date> {


    @Override
    public Collection<String> doSharding(Collection<String> availableTargetNames, RangeShardingValue<Date> shardingValue) {
        Range<Date> valueRange = shardingValue.getValueRange();

        Date lowerDate = valueRange.lowerEndpoint();
        Date uperDate = valueRange.upperEndpoint();

        LinkedHashSet<String> collection = new LinkedHashSet<>();

        Integer lowerYear = Integer.valueOf(new SimpleDateFormat("YYYY").format(lowerDate));
        Integer uperYear = Integer.valueOf(new SimpleDateFormat("YYYY").format(uperDate));
        while(lowerYear <= uperYear){
            if ("2020".equals(lowerYear.toString())) {
                collection.add("db0");
            }
            if ("2021".equals(lowerYear.toString())) {
                collection.add("db1");
            }
            if ("2022".equals(lowerYear.toString())) {
                collection.add("db2");
            }
            lowerYear ++;
        }


        return collection;
    }
}

